package com.warframe.market.riven;

import com.tools.HibernateUtils;
import com.tools.StringContent;
import com.warframe.entity.database.RivenModEO;
import com.warframe.entity.market.riven.RivenMarketMO;
import com.warframe.entity.message.Message;
import com.warframe.message.Executor;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RivenMarket implements Runnable {

    private static String url = "https://riven.market/_modules/riven/showrivens.php?baseurl=Lw==&platform=PC&limit=25&recency=-1&veiled=false&onlinefirst=true&polarity=all&rank=all&mastery=16&weapon=WEAPON_REPLACE&stats=Any&neg=all&price=99999&rerolls=-1&sort=price&direction=ASC&page=1&time=TIME_REPLACE";
    private static String psg = "私聊交易指令：[/w 玩家名 hi,i wtb WEAPON 词缀 for 价格 P from Riven.market ]\n请复制[]中内容，并替换玩家名为交易对象名，词缀为紫卡词缀，价格为交易价格，在游戏内聊天框粘贴发送即可开始交易。";
    private String weapon;
    private String weapon_en;
    private Message message;
    private Boolean otherFlag = true;

    public RivenMarket(Message message) {
        this.weapon = message.getMsg();
        this.message = message;
    }

    private String findWeaponEN() {
        StringBuilder weaponEN = new StringBuilder();
        StringBuilder otherCN = new StringBuilder();
        String stringBuffer = "select * from RivenMod a where a.cn like '%WEAPON%' order by a.cn";

        Session session = HibernateUtils.getSessionFactory().openSession();
        SQLQuery query = session.createSQLQuery(stringBuffer.replace("WEAPON", weapon));
        List<RivenModEO> rivenModEOList = query.addEntity(RivenModEO.class).list();

        if (rivenModEOList.size() > 0) {
            weaponEN.append(rivenModEOList.get(0).getEn());
            weapon_en = weaponEN.toString();
            weapon = rivenModEOList.get(0).getCn();
            rivenModEOList.remove(0);
            for (RivenModEO eachRivenModEO : rivenModEOList) {
                otherCN.append(eachRivenModEO.getCn());
            }
        } else {
            return null;
        }
        String result = null;
        if (weaponEN != null) {
            result = weaponEN.toString() + "|" + otherCN.toString();
        }
        session.close();
        return result;
    }


    //通过网络链接获取信息
    private List<RivenMarketMO> getResult(String weapon) {
        //搜索的url
        if (weapon != null) {
            String keyUrl = url.replace("WEAPON_REPLACE", weapon.replace(" ", "%"));
            keyUrl = keyUrl.replace("TIME_REPLACE", String.valueOf(System.currentTimeMillis()));

            CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建httpClient实例
            HttpGet httpGet = new HttpGet(keyUrl); // 创建httpget实例
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
            CloseableHttpResponse response = null; // 执行http get请求
            try {
                response = httpClient.execute(httpGet);
            } catch (IOException e) {
                message.setMsg("服务器连接超时，请稍后重试。");
                otherFlag = false;
                return null;
            }
            HttpEntity entity = response.getEntity(); // 获取返回实体
            String str = null;
            try {
                str = EntityUtils.toString(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //开始网络请求
            Document document = Jsoup.parse(str);
            Elements elements = document.getElementsByClass("riven ");
            Elements sellers = document.getElementsByClass("attribute seller ");
            List<RivenMarketMO> rivenMarketMOList = new ArrayList<>();
            List<Attributes> attributesList = new ArrayList<>();
            for (Element eachElement : elements) {
                Attributes attributes = eachElement.attributes();
                attributesList.add(attributes);
                RivenMarketMO rivenMarketMO = new RivenMarketMO();
                rivenMarketMO.setWeapon(attributes.get("data-weapon"));
                rivenMarketMO.setName(attributes.get("data-name"));
                rivenMarketMO.setPrice(attributes.get("data-price"));
                rivenMarketMO.setRank(attributes.get("data-rank"));
                rivenMarketMO.setMr(attributes.get("data-mr"));
                rivenMarketMO.setRerolls(attributes.get("data-rerolls"));
                rivenMarketMO.setPolarity(attributes.get("data-polarity"));
                rivenMarketMO.setStatOne(StringContent.RIVENPROPMAP.get(attributes.get("data-stat1")));
                rivenMarketMO.setStatOneVal(attributes.get("data-stat1val"));
                rivenMarketMO.setStatTwo(StringContent.RIVENPROPMAP.get(attributes.get("data-stat2")));
                rivenMarketMO.setStatTwoVal(attributes.get("data-stat2val"));
                rivenMarketMO.setStatThree(StringContent.RIVENPROPMAP.get(attributes.get("data-stat3")));
                rivenMarketMO.setStatThreeVal(attributes.get("data-stat3val"));
                rivenMarketMO.setStatFour(StringContent.RIVENPROPMAP.get(attributes.get("data-stat4")));
                rivenMarketMO.setStatFourVal(attributes.get("data-stat4val"));
                rivenMarketMOList.add(rivenMarketMO);
            }
            Integer count = 0;
            for (Element eachElement : sellers) {
                rivenMarketMOList.get(count).setSeller(eachElement.text());
                count++;
            }
            return rivenMarketMOList;
        } else {
            return null;
        }
    }

    private String explain(List<RivenMarketMO> rivenMarketMOList) {
        StringBuilder result = new StringBuilder();
        Integer count = 0;

        for (RivenMarketMO eachRivenMarketMO : rivenMarketMOList) {
            StringBuilder rivenInfo = new StringBuilder();
            String str = null;
            str = weapon + " " + eachRivenMarketMO.getName() + "\n";
            rivenInfo.append(str);
            str = eachRivenMarketMO.getStatOne() + " : " + eachRivenMarketMO.getStatOneVal() + "\n";
            rivenInfo.append(str);
            str = eachRivenMarketMO.getStatTwo() + " : " + eachRivenMarketMO.getStatTwoVal() + "\n";
            rivenInfo.append(str);
            if (eachRivenMarketMO.getStatThree() != null && eachRivenMarketMO.getStatThreeVal() != null) {
                str = eachRivenMarketMO.getStatThree() + " : " + eachRivenMarketMO.getStatThreeVal() + "\n";
                rivenInfo.append(str);
            }
            if (eachRivenMarketMO.getStatFour() != null && eachRivenMarketMO.getStatFourVal() != null) {
                str = eachRivenMarketMO.getStatFour() + " : " + eachRivenMarketMO.getStatFourVal() + "\n";
                rivenInfo.append(str);
            }
            str = "极性: " + eachRivenMarketMO.getPolarity() + " 洗次: " + eachRivenMarketMO.getRerolls() + "\n";
            rivenInfo.append(str);
            str = "卖家: " + eachRivenMarketMO.getSeller() + " 售价: " + eachRivenMarketMO.getPrice() + "\n";
            rivenInfo.append(str);
            rivenInfo.append("\n");
            result.append(rivenInfo);
            count++;
            if (count >= 5) {
                break;
            }
        }

        return result.toString();
    }

    @Override
    public void run() {
        String weaponNameStr = findWeaponEN();
        Message tips = new Message();
        if (weaponNameStr != null) {
            String weaponName = weaponNameStr.substring(0, weaponNameStr.indexOf("|"));
            String other = weaponNameStr.substring(weaponNameStr.indexOf("|") + 1, weaponNameStr.length());
            List<RivenMarketMO> rivenMarketMOList = getResult(weaponName);
            String sendMsg;
            if (null != rivenMarketMOList) {
                sendMsg = explain(rivenMarketMOList);
            } else {
                sendMsg = message.getMsg();
            }
            message.setMsg(sendMsg);
            message.setSign(StringContent.SENDPERSON);
            if (otherFlag) {
                tips.setFromQQ(message.getFromQQ());
                tips.setSign(StringContent.SENDPERSON);
                tips.setMsg(psg.replace("WEAPON", weapon_en));
            }
        } else {
            message.setMsg("未查询到该武器名称，请检查后重试");
            if (message.getGroupId() != null) {
                message.setSign(StringContent.SENDGROUP);
            } else {
                message.setSign(StringContent.SENDPERSON);
            }
        }
        Executor.getInstance().pushMsg(message);
        if (tips.getSign() != null) {
            Executor.getInstance().pushMsg(tips);
        }
    }
}
